<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .container{
        width:500px;
        margin:100px auto;
        display:flex;
        justify-content:space-between;
    }
    .item{
        width:100px;
        height:50px;
        border:1px solid black;
    }
</style>

<body>
    <div class="container">
        点击切换颜色
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <script>
        let items = document.getElementsByClassName('item');

        //遍历循环拿到元素
        for( let  i = 0 ; i < items.length; i++){
            items[i].addEventListener('click',function(){
                //如果用this的话不会报错
                // this.style.background = 'pink'

                //用var来定义变量i 如果用items[i]的话会报错,这是因为现在的i是3
                // items[i].style.background = 'pink'

                //解决上面的问题的话就用let 来定义变量
                items[i].style.background = 'pink'


            })

        }
        // console.log(window.i);  //3
    </script>
</body>
</html>